import fs from 'fs-extra'
import archiver from 'archiver'
import path from 'path'
import { fileURLToPath } from 'url'
import axios from 'axios'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 确保 zip 目录存在并清空它
const zipDir = path.join(__dirname, 'zip')
if (fs.existsSync(zipDir)) {
  console.log('🗑️ 清理 zip 目录...')
  fs.emptyDirSync(zipDir)
} else {
  fs.ensureDirSync(zipDir)
}

// 创建一个文件以写入
const dateStr = new Date().toISOString().replace(/[:.]/g, '-')
const output = fs.createWriteStream(path.join(zipDir, `dist-${dateStr}.zip`))
const archive = archiver('zip', {
  zlib: { level: 9 }, // 设置压缩级别
})

// 监听所有存档数据都已被写入
output.on('close', () => {
  console.log(`✅ 压缩完成！总共 ${archive.pointer()} 字节`)
  console.log(`📦 文件保存在: ${path.join(zipDir, `dist-${dateStr}.zip`)}`)
  axios.post(
    'http://localhost:3000/unzipFile',
    {
      file: fs.createReadStream(path.join(zipDir, `dist-${dateStr}.zip`)),
    },
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    },
  )
})

// 监听错误
archive.on('error', (err) => {
  throw err
})

// 将输出流管道连接到归档
archive.pipe(output)

// 将整个 dist 目录添加到 zip
archive.directory('dist/', false)

// 完成归档
archive.finalize()
